import sys
sys.path.insert(0, '../../')

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mall.settings")


import django
django.setup()

from utils.goods import get_breadcrumb,get_goods_specs,get_categories
from apps.goods.models import SKU



def generate_detail_html(sku):
    # try:
    #     sku = SKU.objects.get(id=sku_id)
    # except SKU.DoesNotExist:
    #     pass
    breadcrumb = get_breadcrumb(sku.category)
    categories = get_categories()
    # 规格信息
    goods_specs = get_goods_specs(sku)
    # 渲染页面
    context = {
        'categories': categories,
        'breadcrumb': breadcrumb,
        'sku': sku,
        'specs': goods_specs,
    }

    # 加载渲染的模板
    from django.template import loader
    detail_template = loader.get_template('detail.html')
    # 把数据给模板
    detail_html = detail_template.render(context)
    # 把渲染好的html写入文件
    from mall import settings
    import os

    file_path = os.path.join(os.path.dirname(settings.BASE_DIR), "front_end_pc/goods/%s.html"%sku.id)

    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(detail_html)

skus = SKU.objects.all()
for sku in skus:
    generate_detail_html(sku)